package com.g8.pethospitallearnbackend.service.impls;

import com.g8.pethospitallearnbackend.entity.*;
import com.g8.pethospitallearnbackend.exception.CustomException;
import com.g8.pethospitallearnbackend.mapper.*;
import com.g8.pethospitallearnbackend.service.HosStrucService;
import com.g8.pethospitallearnbackend.utils.NewIdGenerateUtil;
import com.g8.pethospitallearnbackend.utils.responseUtil.ResponseStatusEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

import static com.g8.pethospitallearnbackend.utils.NewIdGenerateUtil.getNumber;

@Service
@Slf4j
public class HosStrucServiceImpl implements HosStrucService {

    @Autowired
    DepartmentMapper departmentMapper;

    @Autowired
    StaffMapper staffMapper;

    @Autowired
    MedicineMapper medicineMapper;

    @Autowired
    LabMapper labMapper;

    @Autowired
    VaccineMapper vaccineMapper;

    @Autowired
    HospitalizationMapper hospitalizationMapper;

    @Autowired
    ChargeMapper chargeMapper;

    @Autowired
    CaseMapper caseMapper;


    @Override
    public List<Department> getAllDepart() {
        DepartmentExample departmentExample = new DepartmentExample();
        List<Department> departments = departmentMapper.selectByExampleWithBLOBs(departmentExample);
        return departments;
    }

    @Override
    public List<Staff> getAllStaff() {
        StaffExample staffExample = new StaffExample();
        List<Staff> staff = staffMapper.selectByExample(staffExample);
        return staff;
    }

    @Override
    public List<Medicine> getAllMedicine() {
        MedicineExample medicineExample = new MedicineExample();
        List<Medicine> medicines = medicineMapper.selectByExampleWithBLOBs(medicineExample);
        return medicines;
    }

    @Override
    public List<Lab> getAllLab() {
        LabExample labExample = new LabExample();
        List<Lab> labs = labMapper.selectByExampleWithBLOBs(labExample);
        return labs;
    }

    /**
     * 没用到？
     * @param labIdorName
     * @return
     */
    @Override
    public Lab getLabByIdOrName(String labIdorName) {
        //判断传入的数据是否完整
        if(labIdorName == null || labIdorName.isEmpty()){
            throw new CustomException(ResponseStatusEnum.BAD_REQUEST, "传入的数据为空，请重新传入");
        }

        LabExample labExample = new LabExample();
        labExample.or().andLabIdEqualTo(labIdorName);
        labExample.or().andLabNameEqualTo(labIdorName);
        List<Lab> labs = labMapper.selectByExampleWithBLOBs(labExample);

        //判断返回的lab数量是否正确
        if(labs.size() != 1){
            throw new CustomException(ResponseStatusEnum.BAD_REQUEST, "查找到的数据数量有误/为空，请重新选择");
        }
        Lab lab = labs.get(0);
        return lab;
    }

    @Override
    public List<Vaccine> getAllVaccine() {
        VaccineExample vaccineExample = new VaccineExample();
        List<Vaccine> vaccines = vaccineMapper.selectByExampleWithBLOBs(vaccineExample);
        return vaccines;
    }

    @Override
    public List<Hospitalization> getAllHosp() {
        HospitalizationExample hospitalizationExample = new HospitalizationExample();
        List<Hospitalization> hospitalizations = hospitalizationMapper.selectByExampleWithBLOBs(hospitalizationExample);
        return hospitalizations;
    }

    @Override
    public List<Charge> getAllCharge() {
        ChargeExample chargeExample = new ChargeExample();
        List<Charge> charges = chargeMapper.selectByExampleWithBLOBs(chargeExample);
        return charges;
    }

    @Override
    public Department addDepart(Department department) {
        //获取传入department的具体信息
        String departName  = department.getDepartName();
        String departDesc = department.getDepartDesc();
        String staffId = department.getStaffId();
        String departDevice = department.getDepartDevice();
        String departDevicePic = department.getDevicePic();

        //判断是否传入信息不完整，这里只需要名字不为空
        if(departName == null || departName.isEmpty()){
            throw new CustomException(ResponseStatusEnum.BAD_REQUEST, "科室名字为空，请填写完整");
        }

        //判断科室名字是否重复
        DepartmentExample departmentExample1 = new DepartmentExample();
        departmentExample1.createCriteria().andDepartNameEqualTo(departName);
        List<Department> repeates1 = departmentMapper.selectByExample(departmentExample1);
        if(!repeates1.isEmpty()){
            throw new CustomException(ResponseStatusEnum.BAD_REQUEST, "科室名字重复，请重新添加");
        }

        //判断添加人员是否存在
        if(staffId != null && !staffId.isEmpty()){
//            StaffExample staffExample = new StaffExample();
//            staffExample.createCriteria().andStaffIdEqualTo(staffId);
//            List<Staff> staffs = staffMapper.selectByExample(staffExample);
            Staff staff = staffMapper.selectByPrimaryKey(staffId);
            if(staff == null){
                throw new CustomException(ResponseStatusEnum.BAD_REQUEST, "添加人员信息不存在，请重新添加");
            }
        }

        // 随机生成id
        String id = getNumber(3);
//        DepartmentExample departmentExample = new DepartmentExample();
//        departmentExample.createCriteria().andDepartIdEqualTo(id);
        Department repeats = departmentMapper.selectByPrimaryKey(id);
        while(repeats != null) {
            id = getNumber(3);
            repeats = departmentMapper.selectByPrimaryKey(id);
        }
        department.setDepartId(id);

        departmentMapper.insert(department);

//        return department;
        return departmentMapper.selectByPrimaryKey(staffId);
    }

    @Override
    public Department updateDepart(Department department) {
        String departId = department.getDepartId();
        String departName = department.getDepartName();
        String staffId = department.getStaffId();

        //检查传入信息是否完整
        if(departId == null || departName == null || departId.isEmpty() || departName.isEmpty() ){
            throw new CustomException(ResponseStatusEnum.BAD_REQUEST, "传入科室id或科室名为空，请添加完整");
        }

        //用科室id检查科室是否存在
        Department departmentTemp = departmentMapper.selectByPrimaryKey(departId);
        if(departmentTemp == null){
            throw new CustomException(ResponseStatusEnum.BAD_REQUEST, "该科室不存在，请重新选择");
        }

        //判断科室名字是否重复
        DepartmentExample departmentExample1 = new DepartmentExample();
        departmentExample1.createCriteria().andDepartNameEqualTo(departName).andDepartIdNotEqualTo(departId);
        List<Department> repeates1 = departmentMapper.selectByExample(departmentExample1);
        if(!repeates1.isEmpty()){
            throw new CustomException(ResponseStatusEnum.BAD_REQUEST, "科室名字重复，请重新添加");
        }

        //判断添加人员是否存在
        if(staffId != null && !staffId.isEmpty()){
            Staff staff = staffMapper.selectByPrimaryKey(staffId);
            if(staff == null){
                throw new CustomException(ResponseStatusEnum.BAD_REQUEST, "添加人员信息不存在，请重新添加");
            }
        }

        //数据库更新
        departmentMapper.updateByPrimaryKeyWithBLOBs(department);

//        return department;
        return departmentMapper.selectByPrimaryKey(staffId);
    }

    @Override
    public Staff addStaff(Staff staff) {
        String staffName = staff.getStaffName();
        String staffTitle = staff.getStaffTitle();

        //判断传入staff是否完整，这里看name是否为空
        if(staffName == null || staffName.isEmpty()
                || staffTitle.isEmpty() || staffTitle == null){
            throw new CustomException(ResponseStatusEnum.BAD_REQUEST, "传入信息不完整，请添加完整");
        }

        // 随机生成id
        String id = getNumber(3);
        Staff repeat = staffMapper.selectByPrimaryKey(id);
        while(repeat != null) {
            id = getNumber(3);
            repeat = staffMapper.selectByPrimaryKey(id);
        }
        staff.setStaffId(id);

        //插入数据库
        staffMapper.insert(staff);

//        return staff;
        return staffMapper.selectByPrimaryKey(id);//返回刚才插的
    }

    @Override
    public Charge modifyACharge(Charge charge) {
        if (chargeMapper.selectByPrimaryKey(charge.getChargeId()) == null)
            throw new CustomException(ResponseStatusEnum.DATA_NOT_EXIST, "未查询到待修改收费项目");
        if (charge.getChargeName().isBlank())
            throw new CustomException(ResponseStatusEnum.MISS_PARAM, "收费项目名字不可为空！");
        chargeMapper.updateByPrimaryKey(charge);
        return chargeMapper.selectByPrimaryKey(charge.getChargeId());
    }

    @Override
    public String deleteADepart(String departId) {
        if (departmentMapper.selectByPrimaryKey(departId) == null)
            throw new CustomException(ResponseStatusEnum.DATA_NOT_EXIST, "待删除数据不存在");
        if (departmentMapper.deleteByPrimaryKey(departId) == 1)
            return "删除成功";
        throw new CustomException(ResponseStatusEnum.SYSTEM_ERROR, "删除失败");
    }

    @Override
    public String deleteAStaff(String staffId) {
        if (staffMapper.selectByPrimaryKey(staffId) == null)
            throw new CustomException(ResponseStatusEnum.DATA_NOT_EXIST, "待删除数据不存在");
        if (staffMapper.deleteByPrimaryKey(staffId) == 1)
            return "删除成功";
        throw new CustomException(ResponseStatusEnum.SYSTEM_ERROR, "删除失败");
    }

    @Override
    public String deleteAMedicine(String medicineId) {
        if (medicineMapper.selectByPrimaryKey(medicineId) == null)
            throw new CustomException(ResponseStatusEnum.DATA_NOT_EXIST, "待删除数据不存在");

        //删除前先要判断是否在病例中引用了
        List<String> allMedicineUsed=caseMapper.selectAllMedicine();
        for(String medicine:allMedicineUsed){
            if(medicine.contains(medicineId)){
                throw new CustomException(ResponseStatusEnum.BAD_REQUEST,"该药品在病例中被引用，无法删除！");
            }
        }
        if (medicineMapper.deleteByPrimaryKey(medicineId) == 1)
            return "删除成功";
        throw new CustomException(ResponseStatusEnum.SYSTEM_ERROR, "删除失败");
    }

    @Override
    public String deleteALab(String labId) {
        if (labMapper.selectByPrimaryKey(labId) == null)
            throw new CustomException(ResponseStatusEnum.DATA_NOT_EXIST, "待删除数据不存在");
        List<String> allLabsUsed=caseMapper.selectAllLab();
        for(String lab:allLabsUsed){
            if(lab.contains(labId)){
                throw new CustomException(ResponseStatusEnum.BAD_REQUEST,"该化验项目在病例中被引用，无法删除！");
            }
        }
        if (labMapper.deleteByPrimaryKey(labId) == 1)
            return "删除成功";
        throw new CustomException(ResponseStatusEnum.SYSTEM_ERROR, "删除失败");
    }

    @Override
    public String deleteAVaccine(String vaccineId) {
        if (vaccineMapper.selectByPrimaryKey(vaccineId) == null)
            throw new CustomException(ResponseStatusEnum.DATA_NOT_EXIST, "待删除数据不存在");
        if (vaccineMapper.deleteByPrimaryKey(vaccineId) == 1)
            return "删除成功";
        throw new CustomException(ResponseStatusEnum.SYSTEM_ERROR, "删除失败");
    }

    @Override
    public String deleteAHos(String hosId) {
        if (hospitalizationMapper.selectByPrimaryKey(hosId) == null)
            throw new CustomException(ResponseStatusEnum.DATA_NOT_EXIST, "待删除数据不存在");
        if (hospitalizationMapper.deleteByPrimaryKey(hosId) == 1)
            return "删除成功";
        throw new CustomException(ResponseStatusEnum.SYSTEM_ERROR, "删除失败");
    }

    @Override
    public String deleteACharge(String chargeId) {
        if (chargeMapper.selectByPrimaryKey(chargeId) == null)
            throw new CustomException(ResponseStatusEnum.DATA_NOT_EXIST, "待删除数据不存在");
        if (chargeMapper.deleteByPrimaryKey(chargeId) == 1)
            return "删除成功";
        throw new CustomException(ResponseStatusEnum.SYSTEM_ERROR, "删除失败");
    }

    @Override
    public List<Lab> getAllLabsOfAType(String typeName) {
        LabExample labExample = new LabExample();
        labExample.createCriteria().andLabTypeEqualTo(typeName);
        List<Lab> labs = labMapper.selectByExampleWithBLOBs(labExample);
        if (labs.isEmpty()) throw new CustomException(ResponseStatusEnum.DATA_NOT_EXIST, "该化验项目类型不存在！");
        return labs;
    }

    @Override
    public List<String> getAllLabTypes() {
        List<String> labtypes = labMapper.selectAllLabTypes();
        if (labtypes.isEmpty()) throw new CustomException(ResponseStatusEnum.DATA_NOT_EXIST, "未查询到化验项目的类型");
        return labtypes;
    }

    @Override
    public Staff modifyAStaff(Staff staff) {
        if (staffMapper.selectByPrimaryKey(staff.getStaffId()) == null)
            throw new CustomException(ResponseStatusEnum.DATA_NOT_EXIST, "未查询到待修改人员信息");
        if (staff.getStaffName() == null || staff.getStaffName().isBlank())
            throw new CustomException(ResponseStatusEnum.MISS_PARAM, "人员名字不可为空！");
        int code=staffMapper.updateByPrimaryKey(staff);
        if(code!=1) throw new CustomException(ResponseStatusEnum.SYSTEM_ERROR,"修改人员数据失败");
        return staffMapper.selectByPrimaryKey(staff.getStaffId());
    }

    @Override
    public Medicine addMedicine(Medicine medicine) {
        //判断请求是否合法，medicine名字不能为0
        if(medicine.getMedicineName() == null || medicine.getMedicineName().isBlank())
            throw new CustomException(ResponseStatusEnum.MISS_PARAM,"药品名称不能为空");

        //判断药品名称是否重复
        String medicineName = medicine.getMedicineName();
        MedicineExample medicineExample = new MedicineExample();
        medicineExample.createCriteria().andMedicineNameEqualTo(medicineName);
        List<Medicine> medicines = medicineMapper.selectByExampleWithBLOBs(medicineExample);
        if(!medicines.isEmpty()){
            throw new CustomException(ResponseStatusEnum.MISS_PARAM, "药品名称重复，请修改！");
        }

        String medicineId='m'+getNumber(7);
        medicine.setMedicineId(medicineId);
        int code=medicineMapper.insert(medicine);
        if(code!=1) throw new CustomException(ResponseStatusEnum.SYSTEM_ERROR,"插入药品数据失败");
        return medicineMapper.selectByPrimaryKey(medicineId);
    }

    @Override
    public Medicine modifyAMedicine(Medicine medicine) {
        if (medicineMapper.selectByPrimaryKey(medicine.getMedicineId()) == null)
            throw new CustomException(ResponseStatusEnum.DATA_NOT_EXIST, "未查询到待修改药品信息");
        if (medicine.getMedicineName() == null || medicine.getMedicineName().isBlank())
            throw new CustomException(ResponseStatusEnum.MISS_PARAM, "药品名称不可为空！");

        //判断药品名称是否重复
        String medicineName = medicine.getMedicineName();
        String medicineId = medicine.getMedicineId();
        MedicineExample medicineExample = new MedicineExample();
        medicineExample.createCriteria().andMedicineNameEqualTo(medicineName).andMedicineIdNotEqualTo(medicineId);
        List<Medicine> medicines = medicineMapper.selectByExampleWithBLOBs(medicineExample);
        if(!medicines.isEmpty()){
            throw new CustomException(ResponseStatusEnum.MISS_PARAM, "药品名称重复，请修改！");
        }

        int code=medicineMapper.updateByPrimaryKeyWithBLOBs(medicine);
        if(code!=1) throw new CustomException(ResponseStatusEnum.SYSTEM_ERROR,"修改药品数据失败");
        return medicineMapper.selectByPrimaryKey(medicine.getMedicineId());
    }

    @Override
    public Lab addLab(Lab lab) {
        log.info("正常水平是"+lab.getNormalLevel());
        if(lab.getLabName() == null || lab.getLabName().isBlank() || lab.getLabType() == null || lab.getLabType().isBlank())
            throw new CustomException(ResponseStatusEnum.MISS_PARAM,"化验项目名称和类别不能为空");
        String labId='l'+getNumber(7);
        lab.setLabId(labId);
        int code=labMapper.insert(lab);
        if(code!=1) throw new CustomException(ResponseStatusEnum.SYSTEM_ERROR,"插入化验项目数据失败");
        return labMapper.selectByPrimaryKey(labId);
    }


    @Override
    public Lab modifyALab(Lab lab) {
        if (labMapper.selectByPrimaryKey(lab.getLabId()) == null)
            throw new CustomException(ResponseStatusEnum.DATA_NOT_EXIST, "未查询到待修改化验项目信息");
        if (lab.getLabName() == null || lab.getLabName().isBlank())
            throw new CustomException(ResponseStatusEnum.MISS_PARAM, "化验项目名称不可为空！");
        labMapper.updateByPrimaryKeyWithBLOBs(lab);
        return labMapper.selectByPrimaryKey(lab.getLabId());
    }

    @Override
    public Vaccine addVaccine(Vaccine vaccine) {
        if(vaccine.getVaccineName() == null || vaccine.getVaccineName().isBlank())
            throw new CustomException(ResponseStatusEnum.MISS_PARAM,"疫苗名称不能为空");
        String vaccineId=getNumber(3);
        vaccine.setVaccineId(vaccineId);
        int code=vaccineMapper.insert(vaccine);
        if(code!=1) throw new CustomException(ResponseStatusEnum.SYSTEM_ERROR,"插入疫苗数据失败");
        return vaccineMapper.selectByPrimaryKey(vaccineId);
    }

    @Override
    public Vaccine modifyAVaccine(Vaccine vaccine) {
        if (vaccineMapper.selectByPrimaryKey(vaccine.getVaccineId()) == null)
            throw new CustomException(ResponseStatusEnum.DATA_NOT_EXIST, "未查询到待修改疫苗信息");
        if (vaccine.getVaccineName().isBlank())
            throw new CustomException(ResponseStatusEnum.MISS_PARAM, "疫苗名称不可为空！");
        vaccineMapper.updateByPrimaryKeyWithBLOBs(vaccine);
        return vaccineMapper.selectByPrimaryKey(vaccine.getVaccineId());
    }

    @Override
    public Hospitalization addHospitalization(Hospitalization hospitalization) {
        //hos_pet是外键，和病例id关联，先检验
        List<String> caseIds=caseMapper.selectAllCaseIds();
        if(!caseIds.contains(hospitalization.getHosPet()))
            throw new CustomException(ResponseStatusEnum.BAD_REQUEST,"该宠物信息不存在");
        String hospitalizationId='h'+getNumber(3);
        hospitalization.setHosId(hospitalizationId);
        int code=hospitalizationMapper.insert(hospitalization);
        if(code!=1) throw new CustomException(ResponseStatusEnum.SYSTEM_ERROR,"插入住院数据失败");
        return hospitalizationMapper.selectByPrimaryKey(hospitalizationId);
    }

    @Override
    public Hospitalization modifyAHospitalization(Hospitalization hospitalization) {
        if (hospitalizationMapper.selectByPrimaryKey(hospitalization.getHosId()) == null)
            throw new CustomException(ResponseStatusEnum.DATA_NOT_EXIST, "未查询到待修改住院信息");
        //hos_pet是外键，和病例id关联，先检验
        List<String> caseIds=caseMapper.selectAllCaseIds();
        if(!caseIds.contains(hospitalization.getHosPet()))
            throw new CustomException(ResponseStatusEnum.BAD_REQUEST,"该宠物信息不存在");
        int code=hospitalizationMapper.updateByPrimaryKeyWithBLOBs(hospitalization);
        if(code!=1) throw new CustomException(ResponseStatusEnum.SYSTEM_ERROR,"修改住院数据失败");
        return hospitalizationMapper.selectByPrimaryKey(hospitalization.getHosId());

    }

    @Override
    public Charge addCharge(Charge charge) {
        if(charge.getChargeName().isBlank())
            throw new CustomException(ResponseStatusEnum.MISS_PARAM,"收费项目名称不能为空");
        String chargeId=getNumber(3);
        charge.setChargeId(chargeId);
        int code=chargeMapper.insert(charge);
        if(code!=1) throw new CustomException(ResponseStatusEnum.SYSTEM_ERROR,"插入收费项目数据失败");
        return chargeMapper.selectByPrimaryKey(chargeId);
    }

    @Override
    public Medicine getMedicineByIdOrName(String medicineIdOrName) {
        //判断传入的数据是否完整
        if(medicineIdOrName == null || medicineIdOrName.isEmpty()){
            throw new CustomException(ResponseStatusEnum.BAD_REQUEST, "传入的数据为空，请重新传入");
        }

        MedicineExample medicineExample = new MedicineExample();
        medicineExample.or().andMedicineIdEqualTo(medicineIdOrName);
        medicineExample.or().andMedicineNameEqualTo(medicineIdOrName);
        List<Medicine> medicines = medicineMapper.selectByExampleWithBLOBs(medicineExample);

        //判断返回的medicine数量是否正确
        if(medicines.size() != 1){
            throw new CustomException(ResponseStatusEnum.BAD_REQUEST, "查找到的数据数量有误/为空，请重新选择");
        }
        Medicine medicine = medicines.get(0);
        return medicine;
    }

    @Override
    public Department getDepartmentByIdOrName(String departIdOrName) {
        if(departIdOrName==null||departIdOrName.isEmpty()){
            throw new CustomException(ResponseStatusEnum.BAD_REQUEST,"传入的数据为空，请重新传入");
        }
        DepartmentExample departmentExample=new DepartmentExample();
        departmentExample.or().andDepartIdEqualTo(departIdOrName);
        departmentExample.or().andDepartNameEqualTo(departIdOrName);
        List<Department> departments=departmentMapper.selectByExampleWithBLOBs(departmentExample);

        if(departments.size()!=1){
            throw new CustomException(ResponseStatusEnum.BAD_REQUEST,"查找到的数据数量为0或者有误，请重新请求");
        }
        return departments.get(0);
    }


}
